<script setup>
import router from '@/router'
import { useOrderStore, useUserStore } from '@/stores/index'
import { baseURL } from '@/utils/request'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { WarnTriangleFilled } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'

const orderStore = useOrderStore()
const userStore = useUserStore()
const orderList = ref([])
const fullscreenLoading = ref(false)
const dialogVisible = ref(false)
const innerVisible = ref(false)
const getOrderList = async (id) => {
  await orderStore.getOrderList(id)
  console.log(orderStore.order)
  orderList.value = orderStore.order.filter((item) => item.shopstatic === 0)
  console.log(orderList.value)
}
getOrderList(userStore.user.id)
const formatDate = (isoDateString) => {
  const date = new Date(isoDateString)
  return date.toLocaleString() // 转换为本地时间格式
}

//计算总价
const totalPrice = () => {
  let total = 0
  orderList.value.forEach((item) => {
    total += item.goodprice
  })
  return total
}
//删除订单
const deleteOrder = async (id) => {
  await ElMessageBox.confirm(`你确定要删除吗?`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    icon: WarnTriangleFilled,
    draggable: true
  })
  await orderStore.deleteOrderById(id)
  getOrderList(userStore.user.id)
  ElMessage.success('删除成功')
}

//删除所有订单
const deleteAllOrder = async () => {
  await ElMessageBox.confirm(`你确定要取消该订单吗?`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    icon: WarnTriangleFilled,
    draggable: true
  })
  //遍历所有订单，删除每个订单
  for (let i = 0; i < orderList.value.length; i++) {
    const orderId = orderList.value[i].id
    await orderStore.deleteOrderById(orderId)
  }
  getOrderList(userStore.user.id)
  ElMessage.success('删除成功')
}

//十分钟倒计时
const countdownTime = ref('00:00')
const totalSeconds = 600
countdownTime.value =
  (Math.floor(totalSeconds / 60) < 10
    ? '0' + Math.floor(totalSeconds / 60)
    : Math.floor(totalSeconds / 60)) +
  ':' +
  (totalSeconds % 60 < 10 ? '0' + (totalSeconds % 60) : totalSeconds % 60)

let timer = null

const startCountdown = async () => {
  let secondsLeft = totalSeconds
  timer = setInterval(async () => {
    if (secondsLeft > 1) {
      secondsLeft--
      const minutes = Math.floor(secondsLeft / 60)
      const seconds = secondsLeft % 60
      countdownTime.value = `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`
    } else {
      for (let i = 0; i < orderList.value.length; i++) {
        const orderId = orderList.value[i].id
        await orderStore.deleteOrderById(orderId)
      }
      getOrderList(userStore.user.id)
      clearInterval(timer)
      countdownTime.value = '00:00'
    }
  }, 1000)
}
onMounted(() => {
  startCountdown()
})
const open2 = () => {
  ElNotification({
    title: '支付成功',
    message: '请到游戏库<a href="/boss/library" style="color: #1976D2">查看详情</a>',
    position: 'bottom-right',
    dangerouslyUseHTMLString: true,
    type: 'success',
    duration: 2000
  })
}
const submitOrder = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(async () => {
    for (let i = 0; i < orderList.value.length; i++) {
      await orderStore.submitOrder(orderList.value[i].id)
    }
    await userStore.updateMoney(userStore.user.id, userStore.user.money - totalPrice())
    innerVisible.value = false
    dialogVisible.value = false
    loading.close()
    ElMessage.success('支付成功')
    await getOrderList(userStore.user.id)
    clearInterval(timer)
    await userStore.getUser(userStore.user.id)
    open2()
  }, 2000)
}
</script>

<template>
  <div class="new_conment">
    <div class="center">
      <div class="order">
        <!-- 标题 -->
        <div class="title">
          <h1>未付款订单</h1>
          <a @click="router.push('/myorder')" target="_blank" class="more">转到 我的订单 &gt; </a>
        </div>
        <!-- 未付款订单表结构 -->
        <div class="Unpaidbox" v-if="orderList.length !== 0">
          <div class="tile">
            <div class="link_a"></div>
            <!-- 倒计时 -->
            <div class="timelis">
              支付倒计时：<span id="ordertime0" class="time">{{ countdownTime }}</span>
            </div>
          </div>
          <!-- 表头 -->
          <div class="tr th">
            <div class="td tdname">商品名称</div>
            <div class="right">
              <div class="td tdorder">订单号</div>
              <div class="td tdtime">下单日期</div>
              <div class="td tdcount">优惠</div>
              <div class="td tdtotal">原价</div>
              <div class="td tdstate">订单状态</div>
            </div>
          </div>
          <!-- 订单商品 -->

          <ul v-for="item in orderList" :key="item.id">
            <el-badge value="X" class="item" @click="deleteOrder(item.id)"></el-badge>
            <li class="tr">
              <div class="td tdname">
                <a href="#" target="_blank" class="img"
                  ><img :src="baseURL + '/files/' + item.image" style="display: block" /></a
                ><a href="#" target="_blank" class="name_p"
                  ><span>{{ item.goodname }}</span></a
                >
              </div>
              <div class="td tdorder">{{ item.goodId }}</div>
              <div class="td tdtime">{{ formatDate(item.createtime) }}</div>
              <div class="td tdcount">0</div>
              <div class="td tdtotal">¥{{ item.goodprice }}</div>
              <div class="td tdstate">
                {{ item.shopstatic === 1 ? '已支付' : '未支付' }}
              </div>
            </li>
          </ul>

          <!-- 订单底部 -->
          <div class="totallis">
            <div class="flex1">
              <div class="text_">
                <div class="p p_price">
                  原价：<span>¥{{ totalPrice() }}</span>
                </div>
                <div class="p p_address">快递：<span>0</span></div>
                <div class="p p_count">优惠：<span>0</span></div>
                <div class="p ptotal">
                  总计：<span>¥{{ totalPrice() }}</span>
                </div>
              </div>
            </div>
            <div class="btnbox">
              <a href="javascript:void(0)" class="btn" @click="dialogVisible = true">立即支付</a>
              <a href="javascript:void(0)" class="cancel" @click="deleteAllOrder()">取消订单</a>
            </div>
          </div>
          <el-dialog
            draggable
            v-model="dialogVisible"
            style="border-radius: 20px"
            width="40%"
            :before-close="handleClose"
          >
            <template #default>
              <el-dialog
                draggable
                v-model="innerVisible"
                width="35%"
                style="margin-top: 150px; border-radius: 20px"
                append-to-body
              >
                <div
                  style="margin-bottom: 20px; font-size: 24px; align-items: center; display: flex"
                >
                  <el-icon style="color: red; margin-right: 5px"><WarningFilled /></el-icon>支付确认
                </div>
                <div style="font-size: 20px; margin-bottom: 20px">
                  <span
                    >账户余额变化：<span
                      >¥<span style="color: green">{{ userStore.user.money }}</span> -
                      <span style="color: red">{{ totalPrice() }}</span>
                    </span></span
                  >
                  <el-icon style="margin: 0 10px"><Switch /></el-icon>
                  <span style="color: #27b5f2"
                    >¥{{ userStore.user.money - totalPrice()
                    }}<span
                      ><el-icon style="color: red"><Bottom /></el-icon></span
                  ></span>
                </div>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="innerVisible = false">取消</el-button>
                    <el-button
                      type="primary"
                      @click="submitOrder()"
                      v-loading.fullscreen.lock="fullscreenLoading"
                      >确定支付</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </template>
            <template #title>
              <h1>支付账单</h1>
              <div style="margin-top: 20px; font-size: 24px">
                总计：<span style="color: red">¥{{ totalPrice() }}</span> <br />
                <div style="margin-top: 20px; font-size: 24px">
                  账户余额：<span style="color: green">¥{{ userStore.user.money }}</span>
                </div>
                <div style="margin-top: 20px; font-size: 24px">
                  支付后账户剩余为：<span
                    >¥{{ userStore.user.money - totalPrice() }}
                    <span
                      ><el-icon style="color: red"><Bottom /></el-icon></span
                  ></span>
                </div>
              </div>
            </template>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="innerVisible = true">确定支付</el-button>
              </span>
            </template>
          </el-dialog>
          <!--           <input type="hidden" id="firstorders" value="2408050922005257" />
            <input type="hidden" id="ordersstr" value="2408050922005257" />
            <input type="hidden" id="channel_id" value="3" />
            <input type="hidden" id="paytype" value="2" />
            <input type="hidden" id="name" value="" />
            <input type="hidden" id="telephone" value="" />
            <input type="hidden" id="addr" value="" />
            <input type="hidden" id="remark" value="备注" /> -->
        </div>
        <template v-else>
          <el-empty description="您还没有添加订单" />
        </template>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.new_conment {
  padding-top: 40px;
  width: 1200px;
  margin: 0 auto;

  .center {
    padding: 0 20px;

    .order {
      .title {
        position: relative;
        display: flex;

        h1 {
          margin-left: 10px;
        }

        .more {
          position: absolute;
          right: 0;
          top: 0;
          margin-right: auto;
          line-height: 85px;
          cursor: pointer;

          &:hover {
            color: #de4815;
          }
        }
      }

      .Unpaidbox {
        margin-top: 20px;
        margin-bottom: 50px;
        padding: 20px;
        background-color: #fff;
        border-radius: 15px;

        .tile {
          margin-top: 10px;
          margin-bottom: 50px;
          display: flex;

          .timelis {
            font-size: large;
            margin-left: auto;
            margin-right: 20px;

            .time {
              font-size: medium;
              color: #de4815;
            }
          }
        }

        .tr.th {
          display: flex;
          margin-left: 20px;

          .td.tdname {
            width: 400px;
          }

          .right {
            flex: 1;
            display: flex;
            margin-right: 10px;
            align-items: center;
            justify-content: space-around;

            .td.tdorder {
              width: 150px;
              margin-left: 10px;
            }

            .td.tdtime {
              width: 150px;
            }
          }
        }

        .item {
          position: relative;
          right: -1078px;
          transform: translateY(-20px);
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-20px) scale(0.95);
            color: #000;
          }
        }
        ul {
          background-color: rgb(245, 248, 250);
          border-radius: 20px;
          padding: 20px;
          margin-bottom: 20px;

          .tr {
            display: flex;
            width: 100%;

            justify-content: space-between;

            .tdname {
              display: flex;
              align-items: center;

              .img {
                img {
                  width: 180px;
                  height: 120px;
                  object-fit: cover;
                  border-radius: 15px;
                  margin-right: 20px;
                  transition: all 0.3s ease;

                  &:hover {
                    transform: scale(1.1);
                  }
                }
              }

              .name_p {
                font-size: 16px;
                width: 180px;

                &:hover {
                  color: #de4815;
                }
              }
            }

            .td {
              display: flex;
              margin-right: 20px;
              align-items: center;
              justify-content: space-around;
            }

            .td.tdtotal {
              font-size: 20px;
              font-weight: bold;
            }
          }
        }

        .totallis {
          display: flex;
          margin-top: 40px;
          margin-bottom: 10px;

          .flex1 {
            flex: 1;
            display: flex;

            .text_ {
              margin-top: 20px;
              margin-bottom: 20px;
              margin-left: auto;
              display: flex;

              .p {
                margin-right: 30px;
                line-height: 30px;
              }

              .p.ptotal {
                font-size: 30px;
                font-weight: bold;
              }
            }
          }

          .btnbox {
            display: flex;
            flex-direction: column;
            width: 300px;
            align-items: center;
            justify-content: space-around;

            .btn {
              height: 40px;
              width: 240px;
              text-align: center;
              line-height: 40px;
              border-radius: 26px;
              border: solid 1px #ff6630;
              background-color: #ffefea;
              color: #ff6630;
              margin-bottom: 20px;
              font-size: 20px;
              transition: all 0.3s ease;

              &:hover {
                transform: scale(0.95);
              }
            }

            .cancel {
              font-size: 16px;
              color: rgb(27, 29, 38);

              &:hover {
                color: #de4815;
              }
            }
          }
        }
      }
    }
  }
}
</style>
